package com.contract

import android.annotation.SuppressLint
import android.app.Application
import android.content.Intent
import cn.woochen.comlib.util.ConfigPref
import cn.woochen.comlib.util.UserPref
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.request.RequestOptions
import com.contract.commonlib.application.ApplicationProxy
import com.contract.commonlib.application.IApplication
import com.contract.commonlib.config.Constants
import com.contract.commonlib.http.RetrofitUtil
import com.contract.commonlib.http.factory.CustomizeGsonConverterFactory
import com.contract.commonlib.http.https.CertificateManageHelper
import com.contract.commonlib.http.intercept.HttpCacheInterceptor
import com.contract.commonlib.http.intercept.HttpCommonInterceptor
import com.contract.commonlib.http.intercept.HttpHeadInterceptor
import com.contract.commonlib.refresh.RefreshManager
import com.contract.commonlib.refresh.SmartRefreshProcessor
import com.contract.commonlib.util.PackageUtil
import com.contract.commonlib.util.ToolUtils
import com.contract.commonlib.util.ext.showToast
import com.contract.spirit.BuildConfig
import com.contract.spirit.R
import com.contract.spirit.ui.login.LoginActivity
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.bugly.crashreport.CrashReport.UserStrategy
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import okhttp3.Interceptor





class AppApplication : Application(), IApplication {
    private val mToken by UserPref(Constants.USER_TOKEN, "")
    override fun onCreate() {
        super.onCreate()
        if (PackageUtil.isMainProcess(this)) {
            ApplicationProxy.instance = this;
            initRetrofit()
            initGlideConfig()
            initBuglyCrash()
            initTBS()
            RefreshManager.init(SmartRefreshProcessor())
        }
    }

    private fun initTBS(){
        val map = HashMap<String, Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)
        QbSdk.initX5Environment(this, null)
    }

    private fun initBuglyCrash() {
        val strategy = UserStrategy(this)
        strategy.appChannel = ToolUtils.getChannel()
        strategy.appVersion = BuildConfig.VERSION_NAME
        strategy.appPackageName = BuildConfig.APPLICATION_ID
        CrashReport.initCrashReport(applicationContext, "81595421f9", !BuildConfig.isRelease, strategy)
    }

    @SuppressLint("VisibleForTests")
    private fun initGlideConfig() {
        val requestOptions: RequestOptions = RequestOptions().error(R.drawable.img_default_drawable)
            .placeholder(R.drawable.img_default_drawable)
        val builder = GlideBuilder().setDefaultRequestOptions(requestOptions)
        Glide.init(this, builder)
    }
    /**
     * 初始化网络请求
     */
    private fun initRetrofit() {
        //retrofit初始化
        val instance = RetrofitUtil.getInstance()
        val interceptorList: List<Interceptor> =
            listOf(HttpCommonInterceptor(), HttpHeadInterceptor())
        instance.timeout(10L).debugMode(!BuildConfig.isRelease).proxy(!BuildConfig.isRelease)
            .interceptors(interceptorList)
            .interceptor(HttpCacheInterceptor())
            .converterFactory(CustomizeGsonConverterFactory.create())
        instance.init(getBaseUrl(), {
            if (!BuildConfig.isRelease) {
                it.sslSocketFactory(
                    CertificateManageHelper.getSSLSocketFactory(),
                    CertificateManageHelper.getTrustManager()
                )
                it.hostnameVerifier(CertificateManageHelper.getHostnameVerifier())
            }
        })
    }

    override fun loginInvalid() {
        kotlin.run {
            showToast("登录已失效，请重新登录", true)
        }
        UserPref.clear()
        val intent = Intent(this, LoginActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        startActivity(intent)
    }


    override fun getBaseUrl(): String {
        val isTest by ConfigPref(Constants.IS_TEST, false)
        if (BuildConfig.DEBUG) {
            return if (isTest) {
                "http://heyue-app.bole18.net"
            } else {
                "http://api.contractspirit.pro"
            }
        }
        return "http://api.contractspirit.pro"
    }

    override fun getApplication(): Application {
        return this
    }


    override fun setEmptyTips(tips: String?) {
    }

    override fun isLogin(): Boolean {
        return mToken.isNotBlank()
    }
}